<template>
  <view 
    class="container"
    @touchstart="onTouchStart"
    @touchmove="onTouchMove"
    @touchend="onTouchEnd"
  >
    <!-- 分页容器 -->
    <view 
      class="page-container" 
      :style="{ transform: `translateY(-${currentPage * 100}vh)` }"
    >
      <!-- 第一页：基本信息 -->
      <view class="page page-1">
        <view class="page-content">
          <view class="image-section" @tap="previewImage">
            <image class="stone-image" src="/static/data/1.jpg" mode="widthFix" />
          </view>
          
          <view class="info-section">
            <!-- 年代 -->
            <view class="info-group">
              <view class="info-tags">
                <view class="info-tag dynasty">宋</view>
                <view class="info-tag year">1254年</view>
              </view>
            </view>
            
            <!-- 作者 -->
            <view class="info-group">
              <text class="info-label">作者</text>
              <view class="info-tags">
                <view class="info-tag">朱熹</view>
                <view class="info-tag">男</view>
                <view class="info-tag">1130.9.15—1200.4.23</view>
                <view class="info-tag">徽州府婺源县</view>
                <view class="info-tag">理学家</view>
              </view>
            </view>
            
            <!-- 位置 -->
            <view class="info-group">
              <text class="info-label">位置</text>
              <view class="info-tags">
                <view class="info-tag">九曲溪南侧</view>
                <view class="info-tag">西北向</view>
                <view class="info-tag">距地3.5米</view>
              </view>
            </view>
            
            <!-- 书法 -->
            <view class="info-group">
              <text class="info-label">书法</text>
              <view class="info-tags">
                <view class="info-tag">楷书</view>
                <view class="info-tag">阴刻</view>
              </view>
            </view>
            
            <!-- 大小 -->
            <view class="info-group">
              <text class="info-label">大小</text>
              <view class="info-tags">
                <view class="info-tag">幅面：120×80cm</view>
                <view class="info-tag">字体：8×6cm</view>
              </view>
            </view>
          </view>
        </view>
        
      </view>
      
      <!-- 第二页：原文 -->
      <view class="page page-2">
        <view class="page-content">
          <view class="section-header">
            <text class="section-title">摩崖石刻原文</text>
            <view class="title-line"></view>
          </view>
          <view class="poem-container">
            <text class="poem-text">九曲将穷眼豁然，桑麻雨露见平川。</text>
            <text class="poem-text">渔郎更觅桃源路，除是人间别有天。</text>
            <text class="date-text">甲戌年八月增</text>
          </view>
        </view>
      </view>
      
      <!-- 第三页：题解（从这页开始悬浮原文） -->
      <view class="page page-3">
        <view class="page-content">
          <view class="section-header">
            <text class="section-title">题解</text>
            <view class="title-line"></view>
          </view>
          <view class="content-card">
            <text class="content-text">此题刻位于九曲溪南侧，西北向。作者为朱熹（1130.9.15—1200.4.23）。朱熹，字元晦，又字仲晦，号晦庵，晚称晦翁，谥文，世称朱文公。祖籍徽州府婺源县（今江西省婺源），出生于南剑州尤溪（今属福建省尤溪县）。宋朝著名的理学家、思想家、哲学家、教育家、诗人，闽学派的代表人物，世尊称为朱子。朱熹生前在武夷山生活40余年，不仅在此著书讲学，还游遍武夷山水，写了大量诗歌。至今，朱熹在武夷山留下的摩崖石刻尚存十余方。</text>
          </view>
        </view>
      </view>
      
      <!-- 第四页：词语注释 -->
      <view class="page page-4">
        <view class="page-content">
          <view class="section-header">
            <text class="section-title">词语注释</text>
            <view class="title-line"></view>
          </view>
          <view class="notes-container">
            <view class="note-item">
              <view class="note-number">[1]</view>
              <text class="note-content">见：古同"现"，出现，显露。《史记·刺客列传》："图穷而匕首见。"</text>
            </view>
            <view class="note-item">
              <view class="note-number">[2]</view>
              <text class="note-content">平川：一般指陆地上宽广平坦的地方。但在本文中是地名，指九曲溪尽头的星村一带。在三溪四流的环抱之中，星村平原沃野平畴，一马平川，所以古来都以"平川"做为星村的雅称。</text>
            </view>
            <view class="note-item">
              <view class="note-number">[3]</view>
              <text class="note-content">桃源："桃花源"的省称，出自陶渊明的《桃花源记》，描写一个渔人从桃花林尽头处入一山洞，见秦代避乱者后裔聚居其间，生活安适。后因以"桃花源"指避世隐居处或理想中的美好地方。</text>
            </view>
            <view class="note-item">
              <view class="note-number">[4]</view>
              <text class="note-content">别有天：形容风景奇特，引人入胜。</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 第五页：题刻大意 -->
      <view class="page page-5">
        <view class="page-content">
          <view class="section-header">
            <text class="section-title">题刻大意</text>
            <view class="title-line"></view>
          </view>
          <view class="content-card">
            <text class="content-text">这是《九曲棹歌·九曲》的全文。将要到九曲溪的尽头了，眼界豁然开朗。桑麻蔽野，雨露中的平川愈加显露出来。渔夫更加寻觅通往桃花源的路，那是人间之外另有风景奇特、引人入胜的地方。朱熹在游览九曲溪接近终点时，发现平川的美景，觉得平川和桃花源一样美好。</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 全局悬浮原文（只在第三页及之后显示） -->
    <view class="floating-poem" v-if="currentPage >= 2">
      <scroll-view class="floating-poem-scroll" scroll-y>
        <view class="floating-poem-content">
          <text class="floating-poem-text">九曲将穷眼豁然，桑麻雨露见平川。</text>
          <text class="floating-poem-text">渔郎更觅桃源路，除是人间别有天。</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 全局上滑提示 -->
    <view class="scroll-hint-up" v-if="currentPage > 0" @tap="prevPage">
      <image class="hint-icon" src="/static/detail/up.png" mode="aspectFit" />
    </view>
    
    <!-- 全局下拉提示 -->
    <view class="scroll-hint" v-if="currentPage < totalPages - 1" @tap="nextPage">
      <image class="hint-icon" src="/static/detail/down.png" mode="aspectFit" />
    </view>
    
    <!-- 音频播放器 -->
    <view class="audio-player">
      <view class="audio-btn" @tap="toggleAudio">
        <text class="audio-icon">{{ isPlaying ? '⏸' : '▶' }}</text>
      </view>
      <view class="audio-info" v-if="isPlaying">
        <text class="audio-text">正在播放语音讲解...</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 0,
      totalPages: 5,
      isPlaying: false,
      utterance: null,
      speechSynthesis: null,
      isMiniProgram: false,
      audioContext: null,
      touchStartY: 0,
      touchStartTime: 0,
      touchMoveY: 0,
      isDragging: false
    }
  },
  onLoad() {
    // 检测运行环境
    // #ifdef H5
    if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
      this.speechSynthesis = window.speechSynthesis
    }
    // #endif
    
    // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
    this.isMiniProgram = true
    // #endif
  },
  onUnload() {
    this.stopAudio()
    // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
    if (this.audioContext) {
      this.audioContext.destroy()
      this.audioContext = null
    }
    // #endif
  },
  methods: {
    nextPage() {
      if (this.currentPage < this.totalPages - 1) {
        this.currentPage++
      }
    },
    prevPage() {
      if (this.currentPage > 0) {
        this.currentPage--
      }
    },
    onTouchStart(e) {
      this.touchStartY = e.touches[0].clientY
      this.touchStartTime = Date.now()
      this.isDragging = false
    },
    onTouchMove(e) {
      this.touchMoveY = e.touches[0].clientY
      const deltaY = this.touchMoveY - this.touchStartY
      
      // 向下滑动（下拉）超过阈值时标记为拖拽
      if (deltaY > 30) {
        this.isDragging = true
      }
      // 向上滑动（上拉）超过阈值时标记为拖拽
      else if (deltaY < -30) {
        this.isDragging = true
      }
    },
    onTouchEnd(e) {
      if (!this.isDragging) {
        this.touchStartY = 0
        this.touchMoveY = 0
        return
      }
      
      const deltaY = this.touchMoveY - this.touchStartY
      const deltaTime = Date.now() - this.touchStartTime
      
      // 向下滑动超过50px且时间小于500ms，则翻到下一页
      if (deltaY > 50 && deltaTime < 500 && this.currentPage < this.totalPages - 1) {
        this.nextPage()
      }
      // 向上滑动超过50px且时间小于500ms，则翻到上一页
      else if (deltaY < -50 && deltaTime < 500 && this.currentPage > 0) {
        this.prevPage()
      }
      
      this.isDragging = false
      this.touchStartY = 0
      this.touchMoveY = 0
    },
    previewImage() {
      uni.previewImage({
        urls: ['/static/data/1.jpg'],
        current: '/static/data/1.jpg'
      })
    },
    getSpeechText() {
      const texts = [
        '摩崖石刻原文：',
        '九曲将穷眼豁然，桑麻雨露见平川。',
        '渔郎更觅桃源路，除是人间别有天。',
        '甲戌年八月增',
        '',
        '题解：',
        '此题刻位于九曲溪南侧，西北向。作者为朱熹（1130.9.15—1200.4.23）。朱熹，字元晦，又字仲晦，号晦庵，晚称晦翁，谥文，世称朱文公。祖籍徽州府婺源县（今江西省婺源），出生于南剑州尤溪（今属福建省尤溪县）。宋朝著名的理学家、思想家、哲学家、教育家、诗人，闽学派的代表人物，世尊称为朱子。朱熹生前在武夷山生活40余年，不仅在此著书讲学，还游遍武夷山水，写了大量诗歌。至今，朱熹在武夷山留下的摩崖石刻尚存十余方。',
        '',
        '词语注释：',
        '见：古同"现"，出现，显露。《史记·刺客列传》："图穷而匕首见。"',
        '平川：一般指陆地上宽广平坦的地方。但在本文中是地名，指九曲溪尽头的星村一带。在三溪四流的环抱之中，星村平原沃野平畴，一马平川，所以古来都以"平川"做为星村的雅称。',
        '桃源："桃花源"的省称，出自陶渊明的《桃花源记》，描写一个渔人从桃花林尽头处入一山洞，见秦代避乱者后裔聚居其间，生活安适。后因以"桃花源"指避世隐居处或理想中的美好地方。',
        '别有天：形容风景奇特，引人入胜。',
        '',
        '题刻大意：',
        '这是《九曲棹歌·九曲》的全文。将要到九曲溪的尽头了，眼界豁然开朗。桑麻蔽野，雨露中的平川愈加显露出来。渔夫更加寻觅通往桃花源的路，那是人间之外另有风景奇特、引人入胜的地方。朱熹在游览九曲溪接近终点时，发现平川的美景，觉得平川和桃花源一样美好。'
      ]
      return texts.join('\n')
    },
    toggleAudio() {
      // #ifdef H5
      if (!this.speechSynthesis) {
        uni.showToast({
          title: '您的浏览器不支持语音合成',
          icon: 'none'
        })
        return
      }
      // #endif

      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.playAudio()
      }
    },
    playAudio() {
      // #ifdef H5
      if (!this.speechSynthesis) return

      if (this.utterance && this.speechSynthesis.paused) {
        this.speechSynthesis.resume()
        this.isPlaying = true
        return
      }

      const text = this.getSpeechText()
      this.utterance = new SpeechSynthesisUtterance(text)
      
      this.utterance.lang = 'zh-CN'
      this.utterance.rate = 1.0
      this.utterance.pitch = 1.0
      this.utterance.volume = 1.0

      this.utterance.onstart = () => {
        this.isPlaying = true
      }

      this.utterance.onend = () => {
        this.isPlaying = false
        this.utterance = null
      }

      this.utterance.onerror = (event) => {
        console.error('语音合成错误:', event)
        uni.showToast({
          title: '语音播放失败',
          icon: 'none'
        })
        this.isPlaying = false
        this.utterance = null
      }

      this.speechSynthesis.speak(this.utterance)
      // #endif

      // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
      this.playAudioInMiniProgram()
      // #endif
    },
    async playAudioInMiniProgram() {
      try {
        const text = this.getSpeechText()
        uni.showLoading({
          title: '正在生成语音...'
        })
        
        uni.hideLoading()
        uni.showToast({
          title: '小程序环境需要配置 TTS 服务',
          icon: 'none',
          duration: 3000
        })
      } catch (error) {
        console.error('小程序语音播放错误:', error)
        uni.hideLoading()
        uni.showToast({
          title: '语音播放失败',
          icon: 'none'
        })
      }
    },
    playAudioFile(audioUrl) {
      if (!this.audioContext) {
        this.audioContext = uni.createInnerAudioContext()
        
        this.audioContext.onPlay(() => {
          this.isPlaying = true
          uni.hideLoading()
        })
        
        this.audioContext.onEnded(() => {
          this.isPlaying = false
        })
        
        this.audioContext.onError((err) => {
          console.error('音频播放错误:', err)
          this.isPlaying = false
          uni.hideLoading()
          uni.showToast({
            title: '音频播放失败',
            icon: 'none'
          })
        })
      }
      
      this.audioContext.src = audioUrl
      this.audioContext.play()
    },
    pauseAudio() {
      // #ifdef H5
      if (!this.speechSynthesis || !this.isPlaying) return
      
      if (this.speechSynthesis.speaking && !this.speechSynthesis.paused) {
        this.speechSynthesis.pause()
        this.isPlaying = false
      }
      // #endif
      
      // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
      if (this.audioContext && this.isPlaying) {
        this.audioContext.pause()
        this.isPlaying = false
      }
      // #endif
    },
    stopAudio() {
      // #ifdef H5
      if (!this.speechSynthesis) return
      
      if (this.speechSynthesis.speaking) {
        this.speechSynthesis.cancel()
      }
      this.isPlaying = false
      this.utterance = null
      // #endif
      
      // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
      if (this.audioContext) {
        this.audioContext.stop()
        this.isPlaying = false
      }
      // #endif
    }
  }
}
</script>

<style>
@keyframes flipUp {
  from {
    opacity: 0;
    transform: translateY(100vh) rotateX(90deg);
  }
  to {
    opacity: 1;
    transform: translateY(0) rotateX(0deg);
  }
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes bounceUp {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(10px);
  }
}

.container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
  position: relative;
}

.page-container {
  width: 100%;
  height: 100%;
  transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform;
  transform-style: preserve-3d;
}

.page {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  animation: flipUp 0.6s ease-out;
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  box-sizing: border-box;
}

.page-3 .page-content,
.page-4 .page-content,
.page-5 .page-content {
  padding-top: 20vh; /* 为悬浮原文留出空间（20%屏幕高度） */
}

.image-section {
  width: 100%;
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stone-image {
  width: 100%;
  display: block;
}

.info-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.info-group {
  margin-bottom: 20px;
}

.info-group:last-child {
  margin-bottom: 0;
}

.info-label {
  display: block;
  font-size: 14px;
  font-weight: bold;
  color: #2d5a3d;
  margin-bottom: 10px;
}

.info-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.info-tag {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 13px;
  background: #f1f8e9;
  color: #2d5a3d;
  font-weight: 500;
}

.info-tag.dynasty {
  background: #ff9800;
  color: white;
}

.info-tag.year {
  background: #2196f3;
  color: white;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #2d5a3d;
  margin-right: 15px;
}

.title-line {
  flex: 1;
  height: 2px;
  background: linear-gradient(90deg, #2d5a3d, transparent);
  border-radius: 1px;
}

.poem-container {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
  text-align: center;
}

.poem-text {
  font-size: 18px;
  line-height: 2.2;
  color: #2d5a3d;
  display: block;
  margin-bottom: 8px;
  font-family: 'STKaiti', serif;
  font-weight: 500;
}

.date-text {
  font-size: 16px;
  color: #8b4513;
  display: block;
  margin-top: 20px;
  font-style: italic;
}

.content-card {
  background: white;
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0,0,0,0.08);
  border-left: 4px solid #2d5a3d;
}

.content-text {
  font-size: 15px;
  line-height: 1.8;
  color: #444444;
  display: block;
  text-align: justify;
}

.notes-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.note-item {
  display: flex;
  align-items: flex-start;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.06);
}

.note-number {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #2d5a3d, #4a7c59);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  margin-right: 15px;
  flex-shrink: 0;
  box-shadow: 0 4px 10px rgba(45, 90, 61, 0.3);
}

.note-content {
  font-size: 14px;
  line-height: 1.7;
  color: #555555;
  flex: 1;
}

/* 悬浮原文 */
.floating-poem {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 20vh;
  z-index: 10;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 250, 252, 0.95) 100%);
  backdrop-filter: blur(20px);
  box-shadow: 0 4px 20px rgba(45, 90, 61, 0.15), 0 0 0 1px rgba(45, 90, 61, 0.05);
  border-bottom: 2px solid rgba(45, 90, 61, 0.2);
}

.floating-poem::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, rgba(45, 90, 61, 0.3), transparent);
}

.floating-poem-scroll {
  width: 100%;
  height: 100%;
}

.floating-poem-content {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  padding: 20px;
  min-height: 100%;
  box-sizing: border-box;
}

.floating-poem-text {
  font-size: 20px;
  color: #2d5a3d;
  font-family: 'STKaiti', serif;
  font-weight: 500;
}

/* 下拉提示 */
.scroll-hint {
  position: fixed;
  bottom: 5px;
  left: 50%;
  transform: translateX(calc(-50% - 30px));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99;
  animation: bounce 2s infinite;
  pointer-events: auto;
}

/* 上滑提示 */
.scroll-hint-up {
  position: fixed;
  top: 5px;
  left: 50%;
  transform: translateX(calc(-50% - 30px));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99;
  animation: bounceUp 2s infinite;
  pointer-events: auto;
}

.hint-icon {
  width: 40px;
  height: 40px;
  animation: bounce 1.5s infinite;
}

.scroll-hint-up .hint-icon {
  animation: bounceUp 1.5s infinite;
}

/* 音频播放器 */
.audio-player {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 12px;
}

.audio-btn {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2d5a3d, #4a7c59);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 20px rgba(45, 90, 61, 0.4);
  transition: all 0.3s ease;
}

.audio-btn:active {
  transform: scale(0.95);
  box-shadow: 0 4px 12px rgba(45, 90, 61, 0.3);
}

.audio-icon {
  font-size: 24px;
  color: white;
  font-weight: bold;
}

.audio-info {
  background: rgba(255, 255, 255, 0.95);
  padding: 10px 16px;
  border-radius: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.audio-text {
  font-size: 13px;
  color: #2d5a3d;
  font-weight: 500;
}
</style>

